import React, { useEffect, useRef, useState } from 'react';
import TitleBar from '@/src/components/titleBar';
import { Button, Image, Text, View } from '@tarojs/components';
import { AtTabs, AtTabsPane } from 'taro-ui';
import store from '@/src/store';
import './index.less';
import ArticleItem from '@/src/components/articleItem';
import BottomContainer from '@/src/components/bottomContainer';
import Taro, { useDidShow } from '@tarojs/taro';
import { useRouter } from '@tarojs/taro';
import InfiniteScroll from '@/src/components/infiniteScroll';
import { observer } from 'mobx-react-lite';
import { publishListFun } from '@/src/common/method/userInfoFun';
import CommonBlank from '@/src/components/pageBlank';
import CommentItem from '@/src/components/commentItem';
import VedioItem from '@/src/components/vedioItem';
import finishIcon from '../../assert/mine/finish.png';
import { showToast, StatusToast } from '@/src/components/statusToast';
import { myPublishDelFun } from '@/src/common/method/activityFun';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
interface RouteParams {
  current: string;
  [key: string]: string | undefined;
}

const minePublish = () => {
  const pageNum = 10;
  const { params } = useRouter<RouteParams>();
  const [current, setCurrent] = useState<number>(0);
  const [select, setSelect] = useState<any>(false);
  const [edit, setEdit] = useState<boolean>(false); //是否编辑
  const [dataList, setDataList] = useState<any>([]);
  const [loadingText, setLoadingText] = useState<any>('加载中');
  const [maxPageNum, setMaxPageNum] = useState<number>(0);
  const [pageIndex, setPageIndex] = useState<number>(1);
  const [contentType, setContentType] = useState<string>('DYNAMIC');
  // 一级下拉刷新状态
  const [refresherTriggered, setRefresherTriggered] = useState(false);
  const currentRef = useRef(current);
  const tabList: any = [
    { title: '动态', value: 'DYNAMIC' },
    { title: '文章', value: 'ARTICLE' },
    { title: '视频', value: 'VIDEO' },
  ];
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  //获取我的发布
  const getPublishList = (pageIndex: any, contentType: string) => {
    publishListFun({
      ucUserId: Taro.getStorageSync('userId'),
      currentLogged: true,
      contentKind: 'CIGAR',
      contentType: contentType,
      pageNo: pageIndex,
      pageSize: 10,
    }).then((res: any) => {
      setLoadingText('');
      setMaxPageNum(Math.ceil(res.totalCount / pageNum));
      const nextList =
        pageIndex === 1
          ? res.list || []
          : [...(dataList || []), ...(res.list || [])];

      const processed = nextList.map((item: any) => ({
        ...item,
        select: false,
      }));
      setDataList(processed);
    });
  };
  //首次进入页面获取第一页列表
  useEffect(() => {
    getPublishList(pageIndex, contentType);
  }, []);

  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    const index = pageIndex + 1;
    if (index > maxPageNum) {
      return false;
    }
    setPageIndex(index);
    setLoadingText('加载中...');
    return getPublishList(index, contentType);
  };

  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
  };
  //跳转到文章详情
  const gotoDetail = (item: any, name: string) => {
    if (edit) {
      Taro.showToast({ title: '编辑状态下不能查看详情', icon: 'none' });
      return;
    }
    if (name === 'comment') {
      Taro.navigateTo({
        url: `/subPagesAccount/commentDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
      });
    } else if (name === 'article') {
      Taro.navigateTo({
        url: `/subPagesAccount/articleDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
      });
    } else if (name === 'userCenter') {
      Taro.navigateTo({
        url: `/subPagesAccount/userCenter/index?contentKind=${item.contentKind}&&contentType=${item.contentType}&&userId=${item.userInfoVo.ucUserId}`,
      });
    } else {
      //跳转到视频详情
      Taro.navigateTo({
        url: `/subPagesAccount/vedioDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&from=mine&&contentType=${item.contentType}`,
      });
    }
  };
  //选择/取消
  const handleSelectClick = (data: any) => {
    const newDataList: any = dataList.map((item: any) => {
      if (item.contentId === data.contentId) {
        return {
          ...item,
          select: !item.select,
        };
      }
      return item;
    });
    //判断选中的数量和总数量相同，则将全选按钮勾选
    const selectNum = newDataList.filter((item: any) => item.select).length;
    if (selectNum === newDataList.length) {
      setSelect(true);
    } else {
      setSelect(false);
    }
    setDataList([...newDataList]);
  };
  console.log(currentRef.current === 1, 'current========');
  //列表内容
  const content = () => {
    return (
      <View>
        {dataList &&
          dataList.map((item: any, index: any) => {
            return (
              <View key={`${item.contentType}-${index}`}>
                {currentRef.current === 0 && (
                  <CommentItem
                    mine={true}
                    edit={edit}
                    data={item}
                    handleSelect={() => handleSelectClick(item)}
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                  />
                )}
                {currentRef.current === 1 && (
                  <ArticleItem
                    mine={true}
                    edit={edit}
                    data={item}
                    home={true}
                    handleSelect={() => handleSelectClick(item)}
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                  />
                )}
                {currentRef.current === 2 && (
                  <VedioItem
                    mine={true}
                    edit={edit}
                    data={item}
                    home={true}
                    handleSelect={() => handleSelectClick(item)}
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                  />
                )}
              </View>
            );
          })}
        {dataList.length === 0 && loadingText === '' && (
          <CommonBlank desc="暂无内容" visible={true} />
        )}
      </View>
    );
  };
  //切换tab

  const handleTabClick = (index: any) => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    currentRef.current = index;
    setCurrent(index);
    setContentType(tabList[index].value);
    getPublishList(1, tabList[index].value);
    setSelect(false);
  };
  // 每当 current 变化时，更新 ref 的值
  useEffect(() => {
    currentRef.current = current;
  }, [current]);
  // 全选
  const handleSelectAll = (select: boolean) => {
    setSelect(select);
    const newDataList: any = dataList.map((item: any) => {
      return {
        ...item,
        select: select,
      };
    });
    setDataList([...newDataList]);
  };

  // 删除
  const handleDelete = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    let contentDelRequest: any = [];
    const newDataList: any = dataList.filter((item: any) => {
      return item.select;
    });
    newDataList.map((item: any) => {
      contentDelRequest.push({
        allId: item.allId,
        contentId: item.contentId,
        contentKind: item.contentKind,
        contentType: item.contentType,
      });
    });
    myPublishDelFun({
      ucUserId: Taro.getStorageSync('userId'),
      currentLogged: true,
      contentDelRequest: contentDelRequest,
    }).then((res: any) => {
      if (String(res.code) === '0') {
        //调用删除接口
        showToast('删除成功', 'success', 3);
        setEdit(false);
        setSelect(false);
        //刷新列表
        getPublishList(1, contentType);
      } else {
        showToast('删除失败', 'success', 3);
      }
    });
  };
  // 一级下拉刷新处理
  const handleRefreshFun = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('加载中...');
    setRefresherTriggered(true);
    setSelect(false);
    //是否是首次下拉刷新
    getPublishList(1, contentType);
    setTimeout(() => {
      setRefresherTriggered(false);
    }, 1000);
  };
  // 顶部
  const { windowHeight, screenWidth } = Taro.getSystemInfoSync();
  const rpx2px = (rpx: number) => (rpx / 750) * screenWidth;
  const contentPx =
    windowHeight -
    rpx2px(store.commonStore.safeAreaTop) -
    store.commonStore.safeAreaBottom;
  return (
    <View
      className={`mine-publish-container mine-publish-container-${store.commonStore.isIos}`}
      style={{
        paddingTop: `${store.commonStore.pageAreaTop}rpx`,
      }}
    >
      <TitleBar title="我的发布" showLeftBack={true} />
      <View className="mine-publish-content">
        {/* 头部导航 */}
        <View className="mine-publish-content-header">
          <AtTabs
            tabList={tabList}
            current={current}
            className="common-tab"
            onClick={handleTabClick}
            swipeable={false}
            animated={true}
          >
            <AtTabsPane current={current} index={0}>
              <View style={{ height: `${contentPx}px` }}>
                <InfiniteScroll
                  style={{ height: '100%' }}
                  hasMore={pageIndex < maxPageNum}
                  loadMore={() => loadMore()}
                  dataList={dataList}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                  loading={loadingText === '' ? false : true}
                  content={content()}
                />
              </View>
              <BottomContainer />
            </AtTabsPane>
            <AtTabsPane current={current} index={1}>
              <View style={{ height: `${contentPx}px` }}>
                <InfiniteScroll
                  style={{ height: '100%' }}
                  hasMore={pageIndex < maxPageNum}
                  loadMore={() => loadMore()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                  dataList={dataList}
                  loading={loadingText === '' ? false : true}
                  content={content()}
                />
              </View>
              <BottomContainer />
            </AtTabsPane>
            <AtTabsPane current={current} index={2}>
              <View style={{ height: `${contentPx}px` }}>
                <InfiniteScroll
                  style={{ height: '100%' }}
                  hasMore={pageIndex < maxPageNum}
                  loadMore={() => loadMore()}
                  refresherTriggered={refresherTriggered}
                  handleRefresh={() => handleRefreshFun()}
                  dataList={dataList}
                  loading={loadingText === '' ? false : true}
                  content={content()}
                />
              </View>
              <BottomContainer />
            </AtTabsPane>
          </AtTabs>

          {/* 管理按钮在顶部右侧 */}
          <View className="mine-publish-manage" onClick={() => setEdit(!edit)}>
            {edit ? (
              <Image className="edit" src={finishIcon} />
            ) : (
              <Image
                className="done"
                src={
                  'https://file.linkcook.cn/image/wineMiniProgram/mine/edit.png'
                }
              />
            )}
            {edit ? <Text>完成</Text> : <Text>管理</Text>}
          </View>
        </View>
      </View>
      {/* 删除功能 */}
      {edit && (
        <View className="delete-btn">
          <View
            className="delete-btn-left"
            onClick={() => handleSelectAll(!select)}
          >
            <Image
              className="delete-btn-img"
              src={
                select
                  ? 'https://file.linkcook.cn/image/wineMiniProgram/login/checked.png'
                  : 'https://file.linkcook.cn/image/wineMiniProgram/login/unchecked.png'
              }
            />
            <Text className="delete-btn-text">全选</Text>
          </View>
          <View className="delete-btn-right" onClick={() => handleDelete()}>
            <Button className="delete-btn-text">删除</Button>
          </View>
        </View>
      )}
      <BottomContainer />
    </View>
  );
};

export default observer(minePublish);
